<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class MealHelpOrder extends Model
{
    protected $dateFormat = 'U';
    //
    protected $table = "lexiang_meal_help_order";

    public function add($data)
    {
    	DB::beginTransaction();
    	try {
	    	$this->order_number = $this->createOrderNumber();
	    	$this->users_id = $data['users_id'];
	    	$this->amount = $data['amount'];
	    	$this->wx_order_number = $data['wx_order_number'] ?? '';
	    	$this->is_amount = $data['is_amount'];
	    	
	    	$this->entrust = 0;
	    	$this->to_users_id = $data['to_users_id'];
	    	$mealorder = MealOrder::where('order_id',$data['meal_order_id'])->orWhere('order_number',$data['meal_order_id'])->first();
    		$this->meal_order_id = $mealorder->order_id;
	    	$mealorder->help_user_id = $data['to_users_id'];
	    	if($this->is_amount==1){
	    		$mealorder->help_state = 1;
	    		$this->status = 1;
	    	}else{
	    		$this->status = 0;
	    		$mealorder->help_state = 0;
	    	}
	    	
	    	if(!$mealorder->save()){
	    		DB::rollBack();
	    		return [
	    			'success'=>false,
	    			'code'=>"006",
	    			'message'=>'保存出错，请稍后再试！',
	    		];
	    	}
	    	if($this->save()){
	    		DB::commit();
                if($this->is_amount == 1){
                    $sendMsg = [
                        'cates_id'=>$mealorder->cates_id,
                        'shops_id'=>$mealorder->shops_id,
                        'users_id'=>$data['to_users_id'],
                        'order_sernum'=>$mealorder->order_sernum,
                    ];
                    // 微信推送
                    $this->wechatRemind($sendMsg);
                }
	    		return [
	    			'success'=>true,
	    			'code'=>"000",
	    			'message'=>'保存成功',
	    			'data'=>[
	    				'order_number'=>$this->order_number
	    			],
                    'peisong'=>$data['free_peisong'] ?? false
	    		];
	    	}else{
	    		DB::rollBack();
	    		return [
	    			'success'=>false,
	    			'code'=>"006",
	    			'message'=>'保存出错，请稍后再试！',
	    		];
	    	}
    	} catch (\Exception $e) {
    		DB::rollBack();
    		return [
    			'success'=>false,
    			'code'=>"006",
    			'message'=>'保存出错，请稍后再试！',
    		];
    	}
    	
    }

    /**
     * 微信提醒
     */
    public function wechatRemind($data)
    {
        $s = new System;
        $token = $s->get('pro_access_token');
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$token['data']['value']}";
        $catename = MealCate::where('cate_id',$data['cates_id'])->value('cate_name');
        $shopInfo = MealShop::where('shop_id',$data['shops_id'])->first();
        $openid = User::where('user_id',$data['users_id'])->value('small_program_code');
        return curl_post($url,json_encode([
                    'touser'=>$openid,
                    'template_id'=>"TydGcZkR-vUtqJ3Lq7dDdlAb9XWHVhKk9xwWuQ0OSIE",
                    'page'=>"pages/helplist/helplist",
                    'miniprogram_state'=>'formal',
                    'data'=>[
                        'character_string1'=>[
                            "value"=>$data['order_sernum']
                        ],
                        'thing4'=>[
                            "value"=>$shopInfo->shop_name
                        ],
                        'thing12'=>[
                            "value"=>$catename
                        ],
                        'time2'=>[
                            "value"=>date('m-d H:i')
                        ],
                        'thing8'=>[
                            "value"=>'请尽快取餐送达'
                        ],
                    ],
                ]));
    }

    public function getPeisong($circleid)
    {
        $starttime = strtotime(date('Y-m-d 00:00:00'));
        $endtime = strtotime(date('Y-m-d 23:59:59'));
        $users = User::where('circle_id',$circleid)->get();
        if($users->count() <= 0){
            return [
                'success'=>false,
                'code'=>'006',
                'message'=>'该商圈没有配送员，请在所处商圈内饭店下单'
            ];
        }
        if($users->count() > 1){
            $cupp = [];
            foreach ($users as $value) {
                $cupp[$value->user_id] = MealOrder::where('help_user_id',$value->user_id)->whereBetween('insert_time',[$starttime,$endtime])->count();
            }
            asort($cupp);
            $first = array_keys($cupp)[0];
        }else{
            $first = $users[0]->user_id;
        }
        return [
            'success'=>true,
            'code'=>'000',
            'message'=>'查询成功',
            'data'=>$first
        ];
    }

    public function getCateImgsAttribute($v){
        return "https://jiashilexiang.oss-cn-beijing.aliyuncs.com/MealCateImgs".$v;
    }

    /**
     * 转购物车数据
     */
    public function getCartCatesAttribute($v)
    {
        if(empty($v)){
            return $v;
        }
        return json_decode($v,true);
    }

    /**
     * 配送人
     */
    public function getHelpToUsernameAttribute($v)
    {
        return User::where('user_id',$this->to_users_id)->value('nicename');
    }

    /**
     * 下单用户
     */
    public function getHelpUserNameAttribute($v)
    {
        return User::where('user_id',$this->users_id)->value('nicename');
    }

    /**
     * 生成订单号
     */
    public function createOrderNumber()
    {
        return time().rand(11111,99999);
    }

    public function getCreatedAtAttribute($v)
    {
    	return date('Y-m-d H:i',$v);
    }

    public function getUpdatedAtAttribute($v)
    {
    	return date('Y-m-d H:i',$v);
    }
}
